package com.ruoyi.pos.api.service.common.impl;

import com.ruoyi.common.enums.HandleStausEnum;
import com.ruoyi.common.enums.PayTypeEnum;
import com.ruoyi.common.enums.YesOrNoEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.fulinmen.PublicKeySecurityUtil;
import com.ruoyi.common.utils.fulinmen.ReturnData;
import com.ruoyi.common.utils.fulinmen.bo.RealtimeTransBo;
import com.ruoyi.common.utils.json.JsonUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pos.api.service.common.IFulinmenService;
import com.ruoyi.pos.web.domain.TTerminalInfo;
import com.ruoyi.pos.web.domain.TTerminalTransFlowInfo;
import com.ruoyi.pos.web.mapper.TTerminalBindInfoMapper;
import com.ruoyi.pos.web.mapper.TTerminalInfoMapper;
import com.ruoyi.pos.web.mapper.TTerminalTransFlowInfoMapper;
import com.ruoyi.pos.web.mapper.TUserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author luobo
 * @title: FulinmenServiceImpl
 * @projectName pos
 * @description: 付临门业务处理类
 * @date 2022-06-13 08:48:10
 */
@Service
@Slf4j
public class FulinmenServiceImpl implements IFulinmenService {
    @Autowired
    private Environment env;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TTerminalTransFlowInfoMapper terminalTransFlowInfoMapper;

    private static final String RESULT_0000_CODE = "0000";
    private static final String RESULT_0000_DESC = "成功";
    private static final String RESULT_0003_CODE = "0003";
    private static final String RESULT_0003_DESC = "sign验证不通过";
    private static final String RESULT_0004_CODE = "0004";
    private static final String RESULT_0004_DESC = "解密失败";
    private String des3Key;
    private String publicKey;
    private String sha1Key;
    @PostConstruct
    public void init() {
        des3Key = env.getProperty("fulinmen.des3Key");
        publicKey = env.getProperty("fulinmen.publicKey");
        sha1Key = env.getProperty("fulinmen.sha1Key");
    }

    //处理对方推送的实时交易数据
    @Override
    public ReturnData realtimeTrans(String body) throws Exception {
        ReturnData returnData = new ReturnData();
        String bodyStr = "";
        try {
            bodyStr = PublicKeySecurityUtil.decript(body, des3Key, publicKey, sha1Key);
        } catch (Exception e) {
            returnData.setResultCode(RESULT_0004_CODE);
            returnData.setResultContent(RESULT_0004_DESC);
        }
        log.info("实时交易解密数据：{}", bodyStr);
        RealtimeTransBo bean = JsonUtils.jsonToPojo(bodyStr, RealtimeTransBo.class);
        TTerminalInfo terminal = terminalInfoMapper.selectTTerminalInfoBySnCode(bean.getSnCode());
        if (null == terminal) {
            returnData.setResultCode(RESULT_0004_CODE);
            returnData.setResultContent("无效终端数据");
            return returnData;
        }
        Date transDate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, bean.getTransDate() + bean.getTransTime());
        if (transDate.before(terminal.getAddTime())) {
            returnData.setResultCode(RESULT_0004_CODE);
            returnData.setResultContent("历史交易记录，不做处理");
            return returnData;
        }
        //处理业务逻辑
        TTerminalTransFlowInfo mapper = new TTerminalTransFlowInfo();
        mapper.setOrderId(bean.getOrderId());
        List<TTerminalTransFlowInfo> list = terminalTransFlowInfoMapper.selectTTerminalTransFlowInfoList(mapper);
        if (null != list && list.size() > 0) {
            returnData.setResultCode(RESULT_0004_CODE);
            returnData.setResultContent("该订单已接收");
        } else { //数据落地
            TTerminalTransFlowInfo flow = new TTerminalTransFlowInfo();
            BeanUtils.copyProperties(bean, flow);
            //交易方式转换
            if ("01".equals(bean.getPosEntry()) || "02".equals(bean.getPosEntry()) || "05".equals(bean.getPosEntry())) { //先判断支付方式、刷卡
                flow.setPayType(PayTypeEnum.SHUAKA_1.getCode());
                if ("00".equals(bean.getCardType())) { //再判断交易卡类型
                    flow.setCardType("1");
                }
            } else { //扫码
                flow.setPayType(PayTypeEnum.SAOMA_2.getCode());
            }
            flow.setId(IdUtils.simpleUUID());
            flow.setCreateTime(DateUtils.getNowDate());
            flow.setIsValid(YesOrNoEnums.YES.getCode());
            flow.setHandleStaus(HandleStausEnum.NO_HANDLE.getCode());
            flow.setTransTime(transDate);
            flow.setTransAmount(flow.getTransAmount().multiply(new BigDecimal(100))); //将元转换为分
            flow.setExtractionFee(flow.getExtractionFee().multiply(new BigDecimal(100))); //将元转换为分
            terminalTransFlowInfoMapper.insertTTerminalTransFlowInfo(flow);
            returnData.setResultCode(RESULT_0000_CODE);
            returnData.setResultContent(RESULT_0000_DESC);
        }
        return returnData;
    }

    @Override
    public ReturnData check(String body) throws Exception {
        ReturnData returnData = new ReturnData();
        try {
            String bodyStr = PublicKeySecurityUtil.decript(body, des3Key, publicKey, sha1Key);
            if(env.getProperty("fulinmen.heartbeat").equals(bodyStr)){
                log.info("心跳验证成功!");
            } else {
                returnData.setResultCode(RESULT_0003_CODE);
                returnData.setResultContent(RESULT_0003_DESC);
            }
        } catch (Exception e) {
            returnData.setResultCode(RESULT_0004_CODE);
            returnData.setResultContent(RESULT_0004_DESC);
        }
        return returnData;
    }
}































